<template>
  <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="850px"
      top="5vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
  >
    <el-form :model="form" :rules="rules" ref="form" label-width="85px">
     <el-row :gutter="20">
       <el-col :span="12">
         <el-form-item label="线路名称" prop="title">
           <el-input v-model="form.title" placeholder="请输入线路名称"></el-input>
         </el-form-item>
       </el-col>

       <el-col :span="12">
         <el-form-item label="虚拟销售量" prop="virtual_sale_count">
           <el-input-number v-model="form.virtual_sale_count" :min="0" :precision="0" style="width: 100%"></el-input-number>
         </el-form-item>
       </el-col>
       <el-col :span="12">
         <el-form-item label="原价" prop="original_price">
           <el-input-number v-model="form.original_price" :min="0" :precision="2" style="width: 100%"></el-input-number>
         </el-form-item>
       </el-col>
       <el-col :span="12">
         <el-form-item label="价格" prop="price">
           <el-input-number v-model="form.price" :min="0" :precision="2" style="width: 100%" @change="onPriceChange"></el-input-number>
         </el-form-item>
       </el-col>
       <el-col :span="12">
         <el-form-item label="排序" prop="sort">
           <el-input-number v-model="form.sort" :min="0" :precision="0" style="width: 100%"></el-input-number>
         </el-form-item>
       </el-col>
       <el-col :span="12">
         <el-form-item label="状态" prop="status">
           <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="正常" inactive-text="禁用"></el-switch>
         </el-form-item>
       </el-col>

       <el-col :span="12">
         <el-form-item label="所属商家" prop="shop_user_id">
           <el-select v-model="form.shop_user_id" placeholder="请选择所属商家" filterable clearable>
             <el-option v-for="item in businessUserOptions" :key="item.id" :label="item.nickname" :value="item.id" />
           </el-select>
         </el-form-item>
       </el-col>

       <!-- 收入分成配置 -->
       <el-col :span="24">
         <el-divider>收入分成配置</el-divider>
       </el-col>

       <el-col :span="12">
         <el-form-item label="商家收入%" prop="rebate_price_shop_percent">
           <el-input-number
               v-model="form.rebate_price_shop_percent"
               :min="0"
               :max="100"
               :precision="2"
               style="width: 100%"
               @change="calculateShopPrice"
               placeholder="百分比">
             <template slot="append">%</template>
           </el-input-number>
         </el-form-item>
       </el-col>
       <el-col :span="12">
         <el-form-item label="商家收入" prop="rebate_price_shop">
           <el-input-number
               v-model="form.rebate_price_shop"
               :min="0"
               :precision="2"
               style="width: 100%"
               @change="calculateShopPercent"
               placeholder="金额">
             <template slot="append">元</template>
           </el-input-number>
         </el-form-item>
       </el-col>

       <el-col :span="12">
         <el-form-item label="平台收入%" prop="rebate_price_platform_percent">
           <el-input-number
             v-model="form.rebate_price_platform_percent"
             :min="0"
             :max="100"
             :precision="2"
             style="width: 100%"
             @change="calculatePlatformPrice"
             placeholder="百分比">
             <template slot="append">%</template>
           </el-input-number>
         </el-form-item>
       </el-col>
       <el-col :span="12">
         <el-form-item label="平台收入" prop="rebate_price_platform">
           <el-input-number
             v-model="form.rebate_price_platform"
             :min="0"
             :precision="2"
             style="width: 100%"
             @change="calculatePlatformPercent"
             placeholder="金额">
             <template slot="append">元</template>
           </el-input-number>
         </el-form-item>
       </el-col>
       <el-col :span="12">
         <el-form-item label="代理收入%" prop="rebate_price_agent_percent">
           <el-input-number
             v-model="form.rebate_price_agent_percent"
             :min="0"
             :max="100"
             :precision="2"
             style="width: 100%"
             @change="calculateAgentPrice"
             placeholder="百分比">
             <template slot="append">%</template>
           </el-input-number>
         </el-form-item>
       </el-col>
       <el-col :span="12">
         <el-form-item label="代理收入" prop="rebate_price_agent">
           <el-input-number
             v-model="form.rebate_price_agent"
             :min="0"
             :precision="2"
             style="width: 100%"
             @change="calculateAgentPercent"
             placeholder="金额">
             <template slot="append">元</template>
           </el-input-number>
         </el-form-item>
       </el-col>
       <el-col :span="12">
         <el-form-item label="二级代理收入%" prop="rebate_price_agent_percent2">
           <el-input-number
             v-model="form.rebate_price_agent_percent2"
             :min="0"
             :max="100"
             :precision="2"
             style="width: 100%"
             @change="calculateAgent2Price"
             placeholder="百分比">
             <template slot="append">%</template>
           </el-input-number>
         </el-form-item>
       </el-col>
       <el-col :span="12">
         <el-form-item label="二级代理收入" prop="rebate_price_agent2">
           <el-input-number
             v-model="form.rebate_price_agent2"
             :min="0"
             :precision="2"
             style="width: 100%"
             @change="calculateAgent2Percent"
             placeholder="金额">
             <template slot="append">元</template>
           </el-input-number>
         </el-form-item>
       </el-col>

       <el-col :span="24">
         <div class="rebate-summary-card">
           <div class="summary-header">
             <h4>收入分成配置汇总</h4>
           </div>
           <div class="summary-content">
             <div class="summary-items">
               <div class="summary-item">
                 <span class="item-label">商家收入：</span>
                 <span class="item-value">{{ form.rebate_price_shop || 0 }}元 ({{ form.rebate_price_shop_percent || 0 }}%)</span>
               </div>
               <div class="summary-item">
                 <span class="item-label">平台收入：</span>
                 <span class="item-value">{{ form.rebate_price_platform || 0 }}元 ({{ form.rebate_price_platform_percent || 0 }}%)</span>
               </div>
               <div class="summary-item">
                 <span class="item-label">代理收入：</span>
                 <span class="item-value">{{ form.rebate_price_agent || 0 }}元 ({{ form.rebate_price_agent_percent || 0 }}%)</span>
               </div>
               <div class="summary-item">
                 <span class="item-label">二级代理收入：</span>
                 <span class="item-value">{{ form.rebate_price_agent2 || 0 }}元 ({{ form.rebate_price_agent_percent2 || 0 }}%)</span>
               </div>
             </div>
             <el-divider></el-divider>
             <div class="summary-total">
               <div class="total-info">
                 <span class="total-label">总分成金额：</span>
                 <span class="total-value">{{ totalRebateAmount }}元</span>
                 <span class="total-label" style="margin-left: 20px;">总分成比例：</span>
                 <span class="total-value">{{ totalRebatePercent }}%</span>
               </div>
               <div class="status-info">
                 <el-tag
                   :type="rebateStatus.isValid ? 'success' : 'danger'"
                   size="small"
                   effect="dark">
                   {{ rebateStatus.message }}
                 </el-tag>
                 <div v-if="!canSubmit && form.title && form.price > 0" class="submit-tip">
                   <el-alert
                     title="无法提交"
                     description="分成配置存在异常，请修正后再提交"
                     type="warning"
                     size="small"
                     :closable="false"
                     show-icon>
                   </el-alert>
                 </div>
               </div>
             </div>
           </div>
         </div>
       </el-col>
       <el-col :span="24">
        <el-form-item label="标题标签" prop="tags">
         <el-select  multiple
                     filterable
                     placeholder="请输入创建"
                     allow-create  v-model="form.tags" >
           <el-option
               v-for="item in tagOptions"
               :key="item"
               :label="item"
               :value="item">
           </el-option>
         </el-select>
       </el-form-item>
       </el-col>
       <el-col :span="24">
         <el-form-item label="内容标签" prop="tags">
           <el-select  multiple
                       filterable
                       placeholder="请输入创建"
                       allow-create  v-model="form.tags2" >
             <el-option
                 v-for="item in tagOptions2"
                 :key="item"
                 :label="item"
                 :value="item">
             </el-option>
           </el-select>
         </el-form-item>
       </el-col>
       <el-col :span="24">
         <el-form-item label="团期" prop="dates">
           <el-select  multiple
                       filterable
                       placeholder="请输入创建"
                       allow-create  v-model="form.dates" >
             <el-option
                 v-for="item in tagOptions3"
                 :key="item"
                 :label="item"
                 :value="item">
             </el-option>
           </el-select>
         </el-form-item>
       </el-col>
       <el-col :span="24">
         <el-form-item label="封面" prop="post_url">
           <UploadFile v-model="form.post_url"></UploadFile>
         </el-form-item>
       </el-col>
       <el-col :span="24">
         <el-form-item label="轮播" prop="image_urls">
           <UploadFile v-model="form.image_urls" :multiple="true"></UploadFile>
         </el-form-item>
       </el-col>
       <el-col :span="24">
         <el-form-item label="线路详情" prop="content">
           <RichEditor v-model="form.content"></RichEditor>
         </el-form-item>
       </el-col>
     </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button
        type="primary"
        @click="submitForm"
        :disabled="!canSubmit"
        :loading="submitting">
        {{ submitting ? '提交中...' : '确 定' }}
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { http } from "@/api";
import RichEditor from "@/components/RichEditor.vue";
import UploadFile from "@/components/UploadFile.vue";
import { CommonUserLevelEnum } from '@/utils/enum';

export default {
  name: "NewsAdd",
  components: {
    RichEditor,
    UploadFile
  },
  data() {
    return {
      dialogVisible: false,
      dialogTitle: "新增线路",
      isEdit: false,
      categoryOptions: [],
      tagOptions: [],
      tagOptions2: [],
      tagOptions3: [],
      shopOptions: [],
      businessUserOptions: [],
      // 防止循环计算的标志
      isCalculating: false,
      // 提交状态
      submitting: false,
      form: {
        title: "",
        price: 0,
        original_price: 0,
        product_category_id: 0,
        ticket_shop_id: 0,
        parent_id: 0,
        content: "",
        virtual_sale_count: 0,
        sort: 0,
        status: 1,
        tags: [],
        tags2: [],
        dates: [],
        post_url: "",
        image_urls: '',
        // 收入分成字段
        rebate_price_platform: 0,
        rebate_price_platform_percent: 0,
        rebate_price_shop: 0,
        rebate_price_shop_percent: 0,
        rebate_price_agent: 0,
        rebate_price_agent_percent: 0,
        rebate_price_agent2: 0,
        rebate_price_agent_percent2: 0,
        shop_user_id: null,
      },
      rules: {
        title: [
          { required: true, message: "请输入线路名称", trigger: "blur" },
          { max: 255, message: "线路名称不能超过255个字符", trigger: "blur" }
        ],
        rebate_price_platform_percent: [
          { type: 'number', min: 0, max: 100, message: "平台收入百分比必须在0-100之间", trigger: "blur" }
        ],
        rebate_price_platform: [
          { type: 'number', min: 0, message: "平台收入必须大于等于0", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const total = Number(this.totalRebateAmount);
              if (total > this.form.price) {
                callback(new Error('总分成金额不能超过产品价格'));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        rebate_price_shop_percent: [
          { type: 'number', min: 0, max: 100, message: "商家收入百分比必须在0-100之间", trigger: "blur" }
        ],
        rebate_price_shop: [
          { type: 'number', min: 0, message: "商家收入必须大于等于0", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const total = Number(this.totalRebateAmount);
              if (total > this.form.price) {
                callback(new Error('总分成金额不能超过产品价格'));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        rebate_price_agent_percent: [
          { type: 'number', min: 0, max: 100, message: "代理收入百分比必须在0-100之间", trigger: "blur" }
        ],
        rebate_price_agent: [
          { type: 'number', min: 0, message: "代理收入必须大于等于0", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const total = Number(this.totalRebateAmount);
              if (total > this.form.price) {
                callback(new Error('总分成金额不能超过产品价格'));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        rebate_price_agent_percent2: [
          { type: 'number', min: 0, max: 100, message: "二级代理收入百分比必须在0-100之间", trigger: "blur" }
        ],
        rebate_price_agent2: [
          { type: 'number', min: 0, message: "二级代理收入必须大于等于0", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const total = Number(this.totalRebateAmount);
              if (total > this.form.price) {
                callback(new Error('总分成金额不能超过产品价格'));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      }
    };
  },
  computed: {
    // 计算总分成金额
    totalRebateAmount() {
      const platform = Number(this.form.rebate_price_platform) || 0;
      const shop = Number(this.form.rebate_price_shop) || 0;
      const agent = Number(this.form.rebate_price_agent) || 0;
      const agent2 = Number(this.form.rebate_price_agent2) || 0;
      return (platform + shop + agent + agent2).toFixed(2);
    },
    // 计算总分成百分比
    totalRebatePercent() {
      const platform = Number(this.form.rebate_price_platform_percent) || 0;
      const shop = Number(this.form.rebate_price_shop_percent) || 0;
      const agent = Number(this.form.rebate_price_agent_percent) || 0;
      const agent2 = Number(this.form.rebate_price_agent_percent2) || 0;
      return (platform + shop + agent + agent2).toFixed(2);
    },
    // 判断分成状态
    rebateStatus() {
      const totalAmount = Number(this.totalRebateAmount);
      const totalPercent = Number(this.totalRebatePercent);
      const price = Number(this.form.price) || 0;

      if (price <= 0) {
        return {
          isValid: false,
          message: '请先设置线路价格'
        };
      }

      if (totalAmount > price) {
        return {
          isValid: false,
          message: `分成金额超出线路价格 ${(totalAmount - price).toFixed(2)}元`
        };
      }

      if (totalPercent > 100) {
        return {
          isValid: false,
          message: `分成百分比超出100% (当前${totalPercent}%)`
        };
      }

      if (totalAmount === 0 && totalPercent === 0) {
        return {
          isValid: true,
          message: '未设置分成配置'
        };
      }

      return {
        isValid: true,
        message: `分成配置正常 (剩余${(price - totalAmount).toFixed(2)}元)`
      };
    },
    // 判断是否可以提交
    canSubmit() {
      // 检查基本字段是否填写
      if (!this.form.title || !this.form.price || this.form.price <= 0) {
        return false;
      }

      // 检查分成配置是否异常
      const validationResult = this.validateRebateConfig();
      return validationResult.isValid && !this.submitting;
    }
  },
  watch: {
    // 监听价格变化，自动重新计算百分比对应的金额
    'form.price': {
      handler(newPrice, oldPrice) {
        if (newPrice !== oldPrice && newPrice > 0 && !this.isCalculating) {
          this.$nextTick(() => {
            this.onPriceChange();
          });
        }
      }
    }
  },
  created() {
    // 查询商家用户
    http.user.list({ user_type: CommonUserLevelEnum.BUSINESS }).then(res => {
      this.businessUserOptions = res.data && res.data ? res.data : [];
    });
  },
  methods: {
    // 根据平台收入百分比计算金额
    calculatePlatformPrice() {
      if (this.isCalculating) return;
      this.isCalculating = true;

      const percent = Number(this.form.rebate_price_platform_percent) || 0;
      const price = Number(this.form.price) || 0;

      // 根据价格和百分比计算金额，价格为0时金额也为0
      this.form.rebate_price_platform = Number(((price * percent) / 100).toFixed(2));

      this.$nextTick(() => {
        this.isCalculating = false;
        this.validateRebateAmount();
      });
    },

    // 根据平台收入金额计算百分比
    calculatePlatformPercent() {
      if (this.isCalculating) return;
      this.isCalculating = true;

      const amount = Number(this.form.rebate_price_platform) || 0;
      const price = Number(this.form.price) || 0;

      if (amount > 0 && price > 0) {
        this.form.rebate_price_platform_percent = Number(((amount / price) * 100).toFixed(2));
      } else if (amount === 0) {
        this.form.rebate_price_platform_percent = 0;
      }

      this.$nextTick(() => {
        this.isCalculating = false;
        this.validateRebateAmount();
      });
    },

    // 根据商家收入百分比计算金额
    calculateShopPrice() {
      if (this.isCalculating) return;
      this.isCalculating = true;

      const percent = Number(this.form.rebate_price_shop_percent) || 0;
      const price = Number(this.form.price) || 0;

      // 根据价格和百分比计算金额，价格为0时金额也为0
      this.form.rebate_price_shop = Number(((price * percent) / 100).toFixed(2));

      this.$nextTick(() => {
        this.isCalculating = false;
        this.validateRebateAmount();
      });
    },

    // 根据商家收入金额计算百分比
    calculateShopPercent() {
      if (this.isCalculating) return;
      this.isCalculating = true;

      const amount = Number(this.form.rebate_price_shop) || 0;
      const price = Number(this.form.price) || 0;

      if (amount > 0 && price > 0) {
        this.form.rebate_price_shop_percent = Number(((amount / price) * 100).toFixed(2));
      } else if (amount === 0) {
        this.form.rebate_price_shop_percent = 0;
      }

      this.$nextTick(() => {
        this.isCalculating = false;
        this.validateRebateAmount();
      });
    },

    // 根据代理收入百分比计算金额
    calculateAgentPrice() {
      if (this.isCalculating) return;
      this.isCalculating = true;

      const percent = Number(this.form.rebate_price_agent_percent) || 0;
      const price = Number(this.form.price) || 0;

      // 根据价格和百分比计算金额，价格为0时金额也为0
      this.form.rebate_price_agent = Number(((price * percent) / 100).toFixed(2));

      this.$nextTick(() => {
        this.isCalculating = false;
        this.validateRebateAmount();
      });
    },

    // 根据代理收入金额计算百分比
    calculateAgentPercent() {
      if (this.isCalculating) return;
      this.isCalculating = true;

      const amount = Number(this.form.rebate_price_agent) || 0;
      const price = Number(this.form.price) || 0;

      if (amount > 0 && price > 0) {
        this.form.rebate_price_agent_percent = Number(((amount / price) * 100).toFixed(2));
      } else if (amount === 0) {
        this.form.rebate_price_agent_percent = 0;
      }

      this.$nextTick(() => {
        this.isCalculating = false;
        this.validateRebateAmount();
      });
    },

    // 根据二级代理收入百分比计算金额
    calculateAgent2Price() {
      if (this.isCalculating) return;
      this.isCalculating = true;
      
      const percent = Number(this.form.rebate_price_agent_percent2) || 0;
      const price = Number(this.form.price) || 0;
      
      // 根据价格和百分比计算金额，价格为0时金额也为0
      this.form.rebate_price_agent2 = Number(((price * percent) / 100).toFixed(2));
      
      this.$nextTick(() => {
        this.isCalculating = false;
        this.validateRebateAmount();
      });
    },

    // 根据二级代理收入金额计算百分比
    calculateAgent2Percent() {
      if (this.isCalculating) return;
      this.isCalculating = true;
      const amount = Number(this.form.rebate_price_agent2) || 0;
      const price = Number(this.form.price) || 0;
      if (amount > 0 && price > 0) {
        this.form.rebate_price_agent_percent2 = Number(((amount / price) * 100).toFixed(2));
      } else if (amount === 0) {
        this.form.rebate_price_agent_percent2 = 0;
      }
      this.$nextTick(() => {
        this.isCalculating = false;
        this.validateRebateAmount();
      });
    },

    // 验证分成金额总和
    validateRebateAmount() {
      if (this.isCalculating) return;

      const totalAmount = Number(this.totalRebateAmount);
      const price = Number(this.form.price) || 0;

      if (totalAmount > price && price > 0) {
        this.$message.warning(`分成总额(${totalAmount}元)超出线路价格(${price}元)，请调整分成配置`);
      }
    },

    // 当价格变化时重新计算所有金额
    onPriceChange() {
      if (this.isCalculating) return;

      // 使用批量计算方法，避免 isCalculating 标志位冲突
      this.batchCalculateAllPrices();
    },

    // 批量计算所有收入金额（避免 isCalculating 冲突）
    batchCalculateAllPrices() {
      this.isCalculating = true;

      const price = Number(this.form.price) || 0;

      // 1. 计算商家收入金额
      const shopPercent = Number(this.form.rebate_price_shop_percent) || 0;
      this.form.rebate_price_shop = Number(((price * shopPercent) / 100).toFixed(2));

      // 2. 计算平台收入金额
      const platformPercent = Number(this.form.rebate_price_platform_percent) || 0;
      this.form.rebate_price_platform = Number(((price * platformPercent) / 100).toFixed(2));

      // 3. 计算代理收入金额
      const agentPercent = Number(this.form.rebate_price_agent_percent) || 0;
      this.form.rebate_price_agent = Number(((price * agentPercent) / 100).toFixed(2));

      // 4. 计算二级代理收入金额
      const agent2Percent = Number(this.form.rebate_price_agent_percent2) || 0;
      this.form.rebate_price_agent2 = Number(((price * agent2Percent) / 100).toFixed(2));

      this.$nextTick(() => {
        this.isCalculating = false;
        this.validateRebateAmount();
      });
    },
    open(row) {
      this.dialogVisible = true;
      if (row) {
        this.isEdit = true;
        this.dialogTitle = "编辑线路";
        http.product.read(row.id).then(res => {
          this.form = {
            ...res.data,
            tags: (res.data.tags || '').split(','),
            tags2: (res.data.tags2 || '').split(','),
            dates: (res.data.dates || '').split(','),
            // 确保分成字段有默认值
            rebate_price_platform: res.data.rebate_price_platform || 0,
            rebate_price_platform_percent: res.data.rebate_price_platform_percent || 0,
            rebate_price_shop: res.data.rebate_price_shop || 0,
            rebate_price_shop_percent: res.data.rebate_price_shop_percent || 0,
            rebate_price_agent: res.data.rebate_price_agent || 0,
            rebate_price_agent_percent: res.data.rebate_price_agent_percent || 0,
            rebate_price_agent2: res.data.rebate_price_agent2 || 0,
            rebate_price_agent_percent2: res.data.rebate_price_agent_percent2 || 0,
          }
          // 重新获取产品列表，以排除当前产品
          // this.getProducts();
        })
      } else {
        this.isEdit = false;
        this.dialogTitle = "新增线路";
        this.form = {
          title: "",
          price: 0,
          original_price: 0,
          product_category_id: 0,
          ticket_shop_id: 0,
          parent_id: 0,
          content: "",
          virtual_sale_count: 0,
          sort: 0,
          status: 1,
          tags: [],
          tags2: [],
          dates: [],
          post_url: "",
          image_urls: '',
          // 收入分成字段
          rebate_price_platform: 0,
          rebate_price_platform_percent: 0,
          rebate_price_shop: 0,
          rebate_price_shop_percent: 0,
          rebate_price_agent: 0,
          rebate_price_agent_percent: 0,
          rebate_price_agent2: 0,
          rebate_price_agent_percent2: 0,
          shop_user_id: null,
        };
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    handleClose() {
      this.dialogVisible = false;
      this.submitting = false;
      this.$refs.form.resetFields();
    },
    // 严格验证分成配置
    validateRebateConfig() {
      const price = Number(this.form.price) || 0;
      const totalAmount = Number(this.totalRebateAmount);
      const totalPercent = Number(this.totalRebatePercent);

      // 检查产品价格是否设置
      if (price <= 0) {
        return {
          isValid: false,
          message: '线路价格必须大于0才能设置分成配置'
        };
      }

      // 检查分成金额是否超出产品价格
      if (totalAmount > price) {
        return {
          isValid: false,
          message: `分成总金额(${totalAmount}元)超出线路价格(${price}元)，超出${(totalAmount - price).toFixed(2)}元，请调整分成配置`
        };
      }

      // 检查分成百分比是否超过100%
      if (totalPercent > 100) {
        return {
          isValid: false,
          message: `分成百分比总和(${totalPercent}%)超出100%，超出${(totalPercent - 100).toFixed(2)}%，请调整分成配置`
        };
      }

      // 检查单项分成配置的合理性
      const platformAmount = Number(this.form.rebate_price_platform) || 0;
      const platformPercent = Number(this.form.rebate_price_platform_percent) || 0;
      const shopAmount = Number(this.form.rebate_price_shop) || 0;
      const shopPercent = Number(this.form.rebate_price_shop_percent) || 0;
      const agentAmount = Number(this.form.rebate_price_agent) || 0;
      const agentPercent = Number(this.form.rebate_price_agent_percent) || 0;
      const agent2Amount = Number(this.form.rebate_price_agent2) || 0;
      const agent2Percent = Number(this.form.rebate_price_agent_percent2) || 0;

      // 检查单项百分比是否超过100%
      if (platformPercent > 100) {
        return {
          isValid: false,
          message: `平台收入百分比(${platformPercent}%)不能超过100%`
        };
      }
      if (shopPercent > 100) {
        return {
          isValid: false,
          message: `商家收入百分比(${shopPercent}%)不能超过100%`
        };
      }
      if (agentPercent > 100) {
        return {
          isValid: false,
          message: `代理收入百分比(${agentPercent}%)不能超过100%`
        };
      }
      if (agent2Percent > 100) {
        return {
          isValid: false,
          message: `二级代理收入百分比(${agent2Percent}%)不能超过100%`
        };
      }

      // 检查单项金额是否超过产品价格
      if (platformAmount > price) {
        return {
          isValid: false,
          message: `平台收入金额(${platformAmount}元)不能超过线路价格(${price}元)`
        };
      }
      if (shopAmount > price) {
        return {
          isValid: false,
          message: `商家收入金额(${shopAmount}元)不能超过线路价格(${price}元)`
        };
      }
      if (agentAmount > price) {
        return {
          isValid: false,
          message: `代理收入金额(${agentAmount}元)不能超过线路价格(${price}元)`
        };
      }
      if (agent2Amount > price) {
        return {
          isValid: false,
          message: `二级代理收入金额(${agent2Amount}元)不能超过线路价格(${price}元)`
        };
      }

      // 检查金额和百分比的一致性（允许小数点精度误差）
      if (platformPercent > 0 && platformAmount > 0) {
        const calculatedAmount = (price * platformPercent / 100).toFixed(2);
        if (Math.abs(Number(calculatedAmount) - platformAmount) > 0.01) {
          return {
            isValid: false,
            message: `平台收入金额(${platformAmount}元)与百分比(${platformPercent}%)不匹配，按百分比计算应为${calculatedAmount}元`
          };
        }
      }

      if (shopPercent > 0 && shopAmount > 0) {
        const calculatedAmount = (price * shopPercent / 100).toFixed(2);
        if (Math.abs(Number(calculatedAmount) - shopAmount) > 0.01) {
          return {
            isValid: false,
            message: `商家收入金额(${shopAmount}元)与百分比(${shopPercent}%)不匹配，按百分比计算应为${calculatedAmount}元`
          };
        }
      }

      if (agentPercent > 0 && agentAmount > 0) {
        const calculatedAmount = (price * agentPercent / 100).toFixed(2);
        if (Math.abs(Number(calculatedAmount) - agentAmount) > 0.01) {
          return {
            isValid: false,
            message: `代理收入金额(${agentAmount}元)与百分比(${agentPercent}%)不匹配，按百分比计算应为${calculatedAmount}元`
          };
        }
      }

      if (agent2Percent > 0 && agent2Amount > 0) {
        const calculatedAmount = (price * agent2Percent / 100).toFixed(2);
        if (Math.abs(Number(calculatedAmount) - agent2Amount) > 0.01) {
          return {
            isValid: false,
            message: `二级代理收入金额(${agent2Amount}元)与百分比(${agent2Percent}%)不匹配，按百分比计算应为${calculatedAmount}元`
          };
        }
      }

      return {
        isValid: true,
        message: '分成配置验证通过'
      };
    },
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          // 严格的分成配置验证 - 不允许任何异常情况提交
          const validationResult = this.validateRebateConfig();
          if (!validationResult.isValid) {
            this.$message.error(validationResult.message);
            return;
          }

          this.submitting = true;
          try {
            const submitData = {
              ...this.form,
              tags: this.form.tags.join(','),
              tags2: this.form.tags2.join(','),
              dates: this.form.dates.join(','),
              // 确保数值类型正确
              rebate_price_platform: Number(this.form.rebate_price_platform) || 0,
              rebate_price_platform_percent: Number(this.form.rebate_price_platform_percent) || 0,
              rebate_price_shop: Number(this.form.rebate_price_shop) || 0,
              rebate_price_shop_percent: Number(this.form.rebate_price_shop_percent) || 0,
              rebate_price_agent: Number(this.form.rebate_price_agent) || 0,
              rebate_price_agent_percent: Number(this.form.rebate_price_agent_percent) || 0,
              rebate_price_agent2: Number(this.form.rebate_price_agent2) || 0,
              rebate_price_agent_percent2: Number(this.form.rebate_price_agent_percent2) || 0,
              type: 2,
            };

            if (this.isEdit) {
              await http.product.update(this.form.id, submitData);
              this.$message.success("更新成功");
            } else {
              await http.product.create(null, submitData);
              this.$message.success("新增成功");
            }
            this.handleClose();
            this.$emit("get-page");
          } catch (error) {
            console.error(error);
            if (error.response && error.response.data && error.response.data.message) {
              this.$message.error(error.response.data.message);
            } else {
              this.$message.error("操作失败，请检查表单数据是否正确");
            }
          } finally {
            this.submitting = false;
          }
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.el-dialog {
  max-height: 90vh;
  overflow: auto;
}
.el-dialog__body {
  max-height: calc(90vh - 120px);
  overflow-y: auto;
}
.tip-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.rebate-summary-card {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  margin: 20px 0;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.summary-header {
  padding: 15px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  border-radius: 8px 8px 0 0;

  h4 {
    margin: 0;
    font-size: 16px;
    color: #303133;
    font-weight: 600;
  }
}

.summary-content {
  padding: 20px;
}

.summary-items {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;

  .item-label {
    font-weight: 500;
    color: #606266;
  }

  .item-value {
    font-weight: 600;
    color: #303133;
  }
}

.summary-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.total-info {
  display: flex;
  align-items: center;
  font-size: 15px;

  .total-label {
    color: #606266;
    font-weight: 500;
  }

  .total-value {
    color: #303133;
    font-weight: 600;
    margin-left: 8px;
  }
}

.status-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 10px;
}

.submit-tip {
  width: 100%;
  margin-top: 10px;
}

.el-divider {
  margin: 15px 0;
}
</style>
